<?php


namespace app\common\model;

class Footprint extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_footprint';
    // 主键ID
    protected $pk = 'f_id';

	public function record($user_id,$product_id){
		$info = $this
			->field($this->pk)
			->where(['user_id'=>$user_id,'product_id'=>$product_id])
			->find();

		if($info){
			$res = $this->save(['add_time'=>time(),'date'=>date("Y-m-d")],[$this->pk=>$info["{$this->pk}"]]);
		}else{
			$res = $this->save([
				'user_id'=>$user_id,
				'product_id'=>$product_id,
				'add_time'=>time(),
				'date'=>date("Y-m-d"),
			]);
		}
		return $res;
	}

    function GetDateList($user_id,$page=1,$limit=5)
    {
        $dates = $this
            ->field('date')
            ->where(['user_id' => $user_id])
            ->order('date desc')
            ->group('date')
            ->page($page,$limit)
            ->select()
            ->toArray();
        if(!$dates){
            return [];
        }

        $dates = array_column($dates,'date','date');
        $datestr = implode(',',$dates);
        $list = $this
            ->alias('f')
            ->field(['p.product_id','p.product_name','p.mprice','p.price','p.imageurl',"FROM_UNIXTIME(f.add_time,'%Y-%m-%d %H:%i:%s') as add_time",'f.date'])
            ->where([
                ['f.user_id','=',$user_id],
                ['f.date','in',$datestr],
                ['p.is_del','=',1],
            ])
            ->leftJoin([
                ['ddt_products p','f.product_id=p.product_id'],
            ])
            ->order('f.date desc,f.add_time desc')
            ->select()
            ->toArray();

        //处理子级
        $data = [];
        foreach ($list as $value){
            $data[$value['date']][] = $value;
        }
        return array_values($data);
    }
}